package com.xiaoshangkou.hellopra.security;


import com.xiaoshangkou.hellopra.pojo.Admin;
import com.xiaoshangkou.hellopra.pojo.Permission;
import com.xiaoshangkou.hellopra.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

//自定义认证授权逻辑
@Service
public class MyUserDetailService implements UserDetailsService {
    @Autowired
    private AdminService adminService;



    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1认证
        Admin admin = adminService.findByAdminName(username);
        System.out.println(admin);

        if (admin==null){
            throw new UsernameNotFoundException("用户不存在");
        }

        if (!admin.isStatus()){
            throw new UsernameNotFoundException("用户不可用");
        }

        //2.授权
        List<Permission> permissions=adminService.findAllPermission(username);
        List<GrantedAuthority> grantedAuthorities=new ArrayList<>();
        for (Permission permission : permissions) {
            grantedAuthorities.add(new SimpleGrantedAuthority(permission.getPermissionDesc()));
        }

        //封装为UserDetails对象
        UserDetails userDetails= User.withUsername(admin.getUsername())//用户名
                .password(admin.getPassword())//密码
                .authorities(grantedAuthorities)//权限
                .build();

        return userDetails;
    }
}
